package com.xiaohe.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiaohe.common.to.mq.OrderTo;
import com.xiaohe.common.to.mq.SeckillOrderTo;
import com.xiaohe.common.utils.R;
import com.xiaohe.common.vo.MemberResponseVo;
import com.xiaohe.gulimall.order.constant.OrderConstant;
import com.xiaohe.gulimall.order.dao.OrderItemDao;
import com.xiaohe.gulimall.order.entity.OrderItemEntity;
import com.xiaohe.gulimall.order.entity.PaymentInfoEntity;
import com.xiaohe.gulimall.order.enume.OrderStatusEnum;
import com.xiaohe.gulimall.order.feign.CartFeignService;
import com.xiaohe.gulimall.order.feign.MemberFeignService;
import com.xiaohe.gulimall.order.feign.WmsFeignService;
import com.xiaohe.gulimall.order.feign.productFeignService;
import com.xiaohe.gulimall.order.interceptor.LoginUserInterceptor;
import com.xiaohe.gulimall.order.service.OrderItemService;
import com.xiaohe.gulimall.order.service.PaymentInfoService;
import com.xiaohe.gulimall.order.to.OrderCreateTo;
import com.xiaohe.gulimall.order.vo.*;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.order.dao.OrderDao;
import com.xiaohe.gulimall.order.entity.OrderEntity;
import com.xiaohe.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private productFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //1、获取当前登录用户的信息
        MemberResponseVo loginUser = LoginUserInterceptor.getLoginUser();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //2、远程查询所有的收获地址
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(loginUser.getId());
            orderConfirmVo.setAddressVos(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //3、远程查询购物车所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentUserItem = cartFeignService.getCurrentUserItem();
            orderConfirmVo.setItems(currentUserItem);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> skuStockVos = (List<SkuStockVo>) skusHasStock.getData("data", new TypeReference<List<SkuStockVo>>() {});
            if (skuStockVos != null && skuStockVos.size() > 0) {
                //将skuStockVos集合转换为map
                Map<Long, Boolean> skuHasStockMap = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(skuHasStockMap);
            }
        },executor);

        //4、查询用户积分
        Integer integration = loginUser.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+loginUser.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        CompletableFuture.allOf(addressFuture,cartFuture).get();
        return orderConfirmVo;
    }

    /*@GlobalTransactional//开启全局事务*/
    @Transactional//开启本地事务
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        //放入本地缓存池里面
        confirmVoThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberResponseVo loginUser = LoginUserInterceptor.getLoginUser();
        responseVo.setCode(0);
        //下单
        //0表示令牌失败1 删除成功
        String script ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //传过来的令牌
        String orderToken = orderSubmitVo.getOrderToken();
//        //查出redis
//        String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId());
//        if(orderToken!=null&& orderToken.equals(redisToken)){
//            //验证通过
//            stringRedisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId());
//        }else {
//            //不通过
//        }
        //执行lua脚本
        //原子验证令牌
        Long res = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId()), orderToken);
        if (res == 0L) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //验证成功
            //1、创建订单
            OrderCreateTo order = createOrder();

            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比,成功
                //3、保存订单
                saveOrder(order);
                //4、锁定库存,只要有异常，回滚事务
                //订单号，所有订单项
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                //TODO 远程锁定库存
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0){
                    //成功
                    responseVo.setOrder(order.getOrder());
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    //删除购物车里的数据
                    return responseVo;
                }else {
                    //失败
//                   //订单创建成功发消息，发送消息给MQ
                    String msg = (String) r.get("msg");
                   // throw new NoStockException(msg);
//                    responseVo.setCode(3);
                    return  responseVo;
                }
            }else {
                //金额对比失败
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn",orderSn);
        OrderEntity orderEntity = this.getOne(queryWrapper);
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if(orderEntity.getStatus() ==OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            update.setId(entity.getId());
            this.updateById(update);
            OrderTo orderTo =new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发给mq
            try {
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other",orderTo);
            } catch (AmqpException e) {
                //TODO 将没有发送成功的消息进行重试发送
            }
        }

    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);
        QueryWrapper<OrderItemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn",orderSn);
        List<OrderItemEntity> list = orderItemService.list(queryWrapper);
        OrderItemEntity itemEntity = list.get(0);

        BigDecimal amount = orderByOrderSn.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(amount.toString());
        payVo.setOut_trade_no(orderByOrderSn.getOrderSn());
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo loginUser = LoginUserInterceptor.getLoginUser();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",loginUser.getId()).orderByDesc("create_time")
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结郭
     * @param asyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //1、保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(asyncVo.getTrade_no());//交易流水号
        paymentInfoEntity.setOrderSn(asyncVo.getOut_trade_no());//订单号
        paymentInfoEntity.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(asyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);
        //2、修改订单的状态
        if(asyncVo.getTrade_status().equals("TRADE_SUCCESS") || asyncVo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功
            String out_trade_no = asyncVo.getOut_trade_no();
            this.baseMapper.updateOrderPayedStatus(out_trade_no,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);

        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(itemEntity);
    }

    //保存订单
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        List<OrderItemEntity> orderItems = order.getOrderItems();
        //订单
        orderDao.insert(orderEntity);
        //订单项
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //订单号
        String orderNo = IdWorker.getTimeId();
        //1、构建订单
        OrderEntity orderEntity = buildOrder(orderNo);
        //2、获取订单项的相关信息
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderNo);
        //3、验价
        computerPrice(orderEntity,orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon =new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额 =每一个订单项的金额之和
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            //优惠劵
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            //积分
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            //打折
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            //总额
            total= total.add(orderItemEntity.getRealAmount());
            //积分信息
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration().toString()));
            //成长值
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth().toString()));
        }
        //订单价格相关的
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分信息
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    //构建订单

    /**
     *
     * @param orderNo 订单号
     * @return
     */
    private OrderEntity buildOrder(String orderNo) {

        MemberResponseVo loginUser = LoginUserInterceptor.getLoginUser();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderNo);
        orderEntity.setMemberId(loginUser.getId());
        //获取收获地址信息
        //从线程池里面获取页面传来的数据
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        //1、运费的相关信息
        FareVo fareResp = (FareVo) fare.getData(new TypeReference<FareVo>() {
        });
        //运费金额
        orderEntity.setFreightAmount(fareResp.getFare());
        //收货人的信息
        orderEntity.setReceiverCity(fareResp.getAddressVo().getCity());
        //详细地址
        orderEntity.setReceiverDetailAddress(fareResp.getAddressVo().getDetailAddress());
        //名字
        orderEntity.setReceiverName(fareResp.getAddressVo().getName());
        //手机号
        orderEntity.setReceiverPhone(fareResp.getAddressVo().getPhone());
        //邮编
        orderEntity.setReceiverPostCode(fareResp.getAddressVo().getPostCode());
        //省
        orderEntity.setReceiverProvince(fareResp.getAddressVo().getProvince());
        //区
        orderEntity.setReceiverRegion(fareResp.getAddressVo().getRegion());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    //构建订单项
    private List<OrderItemEntity> buildOrderItems(String orderNo) {
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserItem = cartFeignService.getCurrentUserItem();
        if (currentUserItem!=null && currentUserItem.size()>0){
            List<OrderItemEntity> itemEntities = currentUserItem.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                //保存订单号
                orderItemEntity.setOrderSn(orderNo);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    //构建某一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息，订单号
        //2、商品的spu
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo data = (SpuInfoVo) r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        //分类id
        itemEntity.setCategoryId(data.getCatalogId());

        //skuId
        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        //商品数量
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【no】
        //5、积分信息
        //成长积分
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());

        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额
        //原来的价格
        BigDecimal multiply = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        //真实金额，原来-优惠的
        BigDecimal realAmount = multiply.subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realAmount);
        return itemEntity;
    }
}